package org.huaiyan.oauth.uaa.controller;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwt;
import io.jsonwebtoken.Jwts;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;

/**
 * <p>
 * 后台用户表 前端控制器
 * </p>
 *
 * @author huaiyan
 * @since 2021-10-18
 */
@RestController
public class TabAdminUserController {
    public static final String USER_INFO = "/user/info";
    public static final String USER_INFO_JWT = "/user/info/jwt";


    /**
     * 没有经过JWT加密根据access_token获取资源
     * @param authentication 认证
     * @date 2021/10/20 13:58
     * @author huaiyan
     * @return java.lang.Object
     */
    @GetMapping(USER_INFO)
    public Object list(Authentication authentication) {
        Object principal = authentication.getPrincipal();
        return principal;
    }

    /**
     * 没有经过JWT加密根据access_token获取资源
     * @param request 认证
     * @date 2021/10/20 13:58
     * @author huaiyan
     * @return java.lang.Object
     */
    @GetMapping(USER_INFO_JWT)
    public Object list(Authentication authentication,HttpServletRequest request) {
        String header = request.getHeader("Authorization");
        String token = header.substring(header.lastIndexOf("bearer") + 7 );
        Claims body = Jwts.parser()
                /**
                 * 防止签名秘钥中存在中文而乱码导致解析不出来JWT令牌
                 */
                .setSigningKey("HUAI-YAN".getBytes(StandardCharsets.UTF_8))
                .parseClaimsJws(token)
                .getBody();
        return body;
    }

}

